package com.itheima.behavior.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.*;

/**
 * 线程池配置
 */
@Configuration
@Slf4j
public class ThreadPoolConfig {

    /**
     * 审核任务线程池
     */
    @Bean("auditThreadPool")
    public ThreadPoolExecutor auditThreadPool() {
        return new ThreadPoolExecutor(
                10,                             // 核心线程数
                20,                             // 最大线程数
                60L,                            // 空闲线程存活时间
                TimeUnit.SECONDS,               // 时间单位
                new LinkedBlockingQueue<>(1000), // 任务队列
                new ThreadFactory() {           // 线程工厂
                    private int count = 0;
                    @Override
                    public Thread newThread(Runnable r) {
                        Thread thread = new Thread(r);
                        thread.setName("audit-thread-" + count++);
                        return thread;
                    }
                },
                new ThreadPoolExecutor.CallerRunsPolicy() // 拒绝策略
        );
    }

    /**
     * 通用任务线程池
     */
    @Bean("commonThreadPool")
    public ThreadPoolExecutor commonThreadPool() {
        return new ThreadPoolExecutor(
                5,
                10,
                60L,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(500),
                new ThreadFactory() {
                    private int count = 0;
                    @Override
                    public Thread newThread(Runnable r) {
                        Thread thread = new Thread(r);
                        thread.setName("common-thread-" + count++);
                        return thread;
                    }
                },
                new ThreadPoolExecutor.CallerRunsPolicy()
        );
    }
}

